package com.example.aiquestions.service.impl;

import com.example.aiquestions.entity.User;
import com.example.aiquestions.mapper.UserMapper;
import com.example.aiquestions.model.dto.LoginResponseDTO;
import com.example.aiquestions.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.time.LocalDateTime;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public LoginResponseDTO login(String username, String password) {
        // 根据用户名查询用户
        User user = userMapper.selectByUsername(username);
        
        // 用户不存在
        if (user == null) {
            return LoginResponseDTO.fail("用户不存在");
        }
        
        // 密码错误
        if (!Objects.equals(user.getPassword(), password)) {
            return LoginResponseDTO.fail("密码错误");
        }
        
        // 检查用户状态
        if (user.getStatus() != 1) {
            return LoginResponseDTO.fail("账号已被禁用");
        }
        
        // 登录成功
        return LoginResponseDTO.success(user);
    }

    @Override
    public LoginResponseDTO createUser(String username, String password, String email) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        // 设置默认值
        user.setStatus(1); // 默认状态为正常
        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        user.setCreatedAt(now);
        user.setUpdatedAt(now);
        userMapper.insert(user);

        return LoginResponseDTO.success(user);
    }

    @Override
    public User updateUser(User user) {
        // 更新时设置更新时间
        user.setUpdatedAt(LocalDateTime.now());
        userMapper.update(user);
        return user;
    }

    @Override
    public boolean deleteUser(Long id) {
        return userMapper.deleteById(id) > 0;
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public User getUserByEmail(String email) {
        return userMapper.selectByEmail(email);
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.selectAll();
    }
} 